package cn.autowired.exam.controller;

import cn.autowired.exam.base.CommonResponse;
import cn.autowired.exam.dto.StudentDto;
import cn.autowired.exam.entity.Student;
import cn.autowired.exam.entity.Teacher;
import cn.autowired.exam.service.ExcelDealService;
import cn.autowired.exam.service.StudentService;
import cn.autowired.exam.service.TeacherService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 *
 *   @description : Student 控制器
 *   ---------------------------------
 */
@RestController
@RequestMapping("/student")
public class StudentController extends AbstractController {
private final Logger logger=LoggerFactory.getLogger(StudentController.class);

    @Autowired
    public StudentService studentService;

    @Autowired
    public ExcelDealService excelDealService;

    @Autowired
    public MsgController msgController;

    @Autowired
    public TeacherService teacherService;


    /**
     * 用户登录
     * @param studentNo 学号
     * @param password 密码
     * @return 成功则返回一组json包含此登录信息的过期时间和用户名,失败则返回400错误
     */
    @PostMapping("/login")
    public ResponseEntity login(String studentNo,String password){
        Student student = new Student();
        student.setPassword(password);
        student.setStudentNo(studentNo);
        Student existStudent = studentService.selectOne(new EntityWrapper<Student>()
        .eq(Student.Field.studentNo,studentNo)
        .eq(Student.Field.password,password));
        if(existStudent!=null){
            HashMap<String, Object> userKey = Maps.newHashMap();
            userKey.put("name",existStudent.getName());
            userKey.put("delayTime",System.currentTimeMillis()+24*60*60*1000);
            userKey.put("creatTime",System.currentTimeMillis());
            userKey.put("studentNo",existStudent.getStudentNo());
            userKey.put("id",existStudent.getId());
            return ResponseEntity.ok(userKey);
        }else {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 补充个人信息
     * @param id
     * @param name
     * @param major
     * @param gradeInfo
     * @param sex
     * @param classInfo
     * @return
     */
    @RequestMapping("/edit")
    public ResponseEntity edit(Integer id,String name,String major,String gradeInfo,Integer sex,String classInfo){
        Student student = studentService.selectById(id);
        student.setName(name);
        student.setMajor(major);
        student.setClassInfo(classInfo);
        student.setGradeInfo(gradeInfo);
        student.setSex(sex);
        boolean b = student.insertOrUpdate();
        if (b) {
            return ResponseEntity.ok(CommonResponse.ok());
        } else {
            return ResponseEntity.ok(CommonResponse.error());
        }

    }

    /**
     * 修改密码
     * @param studentNo 学号
     * @param oldPassWord 旧密码
     * @param newPassWord 新密码
     * @return 成功则 返回data.code = 0 标识 失败则返回400错误
     */
    @PostMapping("/modify")
    public ResponseEntity modifyPassword(String studentNo,String oldPassWord,String newPassWord){
        Student existStudent = studentService.selectOne(new EntityWrapper<Student>()
                .eq(Student.Field.studentNo,studentNo)
                .eq(Student.Field.password,oldPassWord));
        if(existStudent!=null){
            existStudent.setPassword(newPassWord);
            boolean flag = existStudent.updateById();
            return ResponseEntity.ok(flag?CommonResponse.ok():CommonResponse.error());
        }else {
            return ResponseEntity.badRequest().build();
        }

    }

    /**
     * 返回所有的学生列表
     * @return
     */
    @GetMapping("/getAllStudent")
    public ResponseEntity getAllStudent(){
        List<Student> students = studentService.selectList(new EntityWrapper<>());
        for (Student student : students) {

            student.setPassword(null);
        }
        HashMap<Object, Object> hashMap = Maps.newHashMap();
        hashMap.put("msg","success");
        hashMap.put("code",0);
        hashMap.put("count",students.size());
        hashMap.put("data",students);
        return ResponseEntity.ok(hashMap);
    }


    @RequestMapping("/getStudentByStudentNo")
    public ResponseEntity getStudentByStudentNo(String studentNo){
        Student student = studentService.selectByStudentNo(studentNo);
        if (null != student){
            return ResponseEntity.ok(CommonResponse.ok(student));
        }else {
            return ResponseEntity.ok(CommonResponse.error());
        }
    }

    @RequestMapping("/getStudentById")
    public ResponseEntity getStudentByStudentNo(Integer id){
        Student student = studentService.selectById(id);
        if (null != student){
            return ResponseEntity.ok(CommonResponse.ok(student));
        }else {
            return ResponseEntity.ok(CommonResponse.error());
        }
    }

    /**
     * 批量上传学生信息
     * @param multipartFile
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadExcel")
    @ResponseBody
    public ResponseEntity uploadExcel(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String contentType = multipartFile.getContentType();
        String fileName = multipartFile.getOriginalFilename();
        String[] split = fileName.split("\\.");
        String ext = split[split.length - 1];
        String filePath = "/var/"+"studentExcel."+ext;
        File file = new File(filePath);
        byte[] bytes = multipartFile.getBytes();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(bytes);
        fileOutputStream.close();
        HashMap<Object, Object> hashMap = Maps.newHashMap();
        hashMap.put("msg","success");
        hashMap.put("code",0);
        return ResponseEntity.ok(hashMap);
    }


    @GetMapping("/getUploadExcel")
    @ResponseBody
    public ResponseEntity getUploadExcel() throws IOException {
        File file = new File("/var/studentExcel.xlsx");
        HashMap<Object, Object> hashMap = Maps.newHashMap();
        try {
            List<StudentDto> excelData = excelDealService.getExcelData("/var/studentExcel.xlsx");
            hashMap.put("msg","success");
            hashMap.put("code",0);
            hashMap.put("count",excelData.size());
            hashMap.put("data",excelData);
            return ResponseEntity.ok(hashMap);
        } catch (Exception e){
            hashMap.put("msg","Excel文件有误");
            hashMap.put("code",-1);
            return ResponseEntity.badRequest().body(hashMap);
        }
    }

    /**
     * 批量插入学生
     * @return
     */
    @GetMapping("/insertStudents")
    public ResponseEntity insertStudents(){
        File file = new File("/var/studentExcel.xlsx");

        try {
            List<StudentDto> excelData = excelDealService.getExcelData("/var/studentExcel.xlsx");
            List<Student> students = new LinkedList<>();
            for (StudentDto excelDatum : excelData) {
                Student student = new Student();
                student.setName(excelDatum.getName());
                student.setMajor(excelDatum.getMajor());
                student.setStudentNo(excelDatum.getStudentNo());
                student.setGradeInfo(excelDatum.getGradeInfo());
                student.setClassInfo(excelDatum.getClassInfo());
                student.setSex(excelDatum.getSex());
                students.add(student);
            }
            boolean flag = studentService.insertBatch(students);

            return ResponseEntity.ok(flag? CommonResponse.ok():CommonResponse.error());
        } catch (Exception e){
            return ResponseEntity.badRequest().build();
        }

    }

    /**
     * 单个插入学生
     * @param studentNo
     * @param name
     * @param major
     * @return
     */
    @PostMapping("/insertStudent")
    public ResponseEntity insertStudent(String studentNo,String name,String major,String sex,String gradeInfo,String classInfo) {
        Student student = new Student();
        student.setStudentNo(studentNo);
        student.setName(name);
        student.setMajor(major);
        student.setGradeInfo(gradeInfo);
        student.setClassInfo(classInfo);
        student.setSex(sex.equals("0")?0:1);
        student.insertOrUpdate();
        return ResponseEntity.ok(CommonResponse.ok());
    }

    /**
     *  根据学生id 删除学生
     * @return
     */
    @GetMapping("/deleteById")
    public ResponseEntity deleteStudent(Integer id) {
        Student student = new Student();
        student.setId(id);
        boolean flag = student.deleteById();
        return ResponseEntity.ok( flag? CommonResponse.ok():CommonResponse.error());
    }

    /**
     * 发送预约申请
     * @param teacherId
     * @param studentNo
     * @param time
     * @return
     */
    @RequestMapping("/application")
    public ResponseEntity application(Integer teacherId,String studentNo,String time){

        Student student = studentService.selectOne(new EntityWrapper<Student>().eq(Student.Field.studentNo, studentNo));

        return msgController.sendMsg(student==null?"未知学生":student.getName()+"申请于"+time+"与您预约,同意请尽快回复",
                teacherId,
                studentNo,
                true);
    }


    /**
     * 回复预约申请
     * @param teacherId
     * @param studentNo
     * @param time
     * @return
     */
    @RequestMapping("/applicationRes")
    public ResponseEntity applicationRes(Integer teacherId,String studentNo,String time,String place){
        Teacher teacher = teacherService.selectById(teacherId);
        if (teacher==null){
            return ResponseEntity.ok(CommonResponse.error());
        }
        return msgController.sendMsg(teacher.getName()+"同意了您的预约,同意请于"+time+"在"+place+"面聊",teacherId,studentNo,false);
    }
}